package org.chatboleh.bean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.chatboleh.exception.EDMException;

public class Document extends DataObject {

	private List<Page> pagelist;
	private String name;
	
	public Document(long i) {
		super(i);
		this.loadPageList();
	}

	private void loadPageList() {
		try {
			pagelist = new Document_Page().getList("document.id="
					+ this.id);
		} catch (EDMException e) {
			logger.error(e);
		}
	}

	public Document() {
		pagelist = new ArrayList<Page>();
	}

	@Override
	protected String fieldnames() {
		return "name";
	}

	@Override
	public List<Document> getList(String criteria) throws EDMException {
		List<Document> list = new ArrayList<Document>();

		try {
			openConnection();
			prepareStatement(selectlistquery(criteria));
			executeQuery();
			while (resultset.next()) {
				Document doc = new Document();
				doc.id = resultset.getLong("id");
				doc.loadResultSetIntoObject(resultset);
				list.add(doc);
			}
		} catch (SQLException e) {
			throw new EDMException(e);
		} finally {
			closeStatement();
		}
		return list;
	}

	@Override
	protected void loadResultSetIntoObject(ResultSet resultset) {
		try {
			this.name = resultset.getString("name");
		} catch (SQLException e) {
			logger.error(e);
		}
	}

	@Override
	public void prepareUpdate() throws EDMException {
		try {
			ps.setString(1, this.name);
		} catch (SQLException e) {
			throw new EDMException(e);
		}
	}

	@Override
	public void save() throws EDMException {
		super.save();
		for (Page page : pagelist) {
			page.save();
			DocumentPage docpage = new DocumentPage();
			docpage.setDocumentid((int) this.id);
			docpage.setPageid((int) page.id);
			docpage.save();
		}
	}

	@Override
	public void delete() throws EDMException {
		List<DocumentPage> document_page_list = new DocumentPage()
				.getList("documentid=" + this.id);
		for (DocumentPage docpage : document_page_list) {
			docpage.delete();
		}
		document_page_list.clear();
		for (Page page : pagelist) {
			page.delete();
		}
		pagelist.clear();
		super.delete();
	}

	@Override
	protected String tablename() {
		return "document";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
